<template>
  <el-tree
    ref="treeRef"
    node-key="_id"
    :data="treeData"
    highlight-current
    default-expand-all
    :expand-on-click-node="false"
    :props="treeProps"
    @node-click="handleNodeClick"
  >
    <template #default="{ data }">
      <span class="icon" v-if="!data?.children.length">
        <el-icon v-if="data.type == 0"><Folder /></el-icon>
        <el-icon v-if="data.type == 1"><Menu /></el-icon>
        <el-icon v-if="data.type == 2"><Lock /></el-icon>
      </span>
      <span class="icon" v-else @click.stop="handleIconClick(data)">
        <el-icon v-if="isOpen(data)"><Remove /></el-icon>
        <el-icon v-else><CirclePlus /></el-icon>
      </span>
      <span>{{ data.title }}</span>
    </template>
  </el-tree>
</template>

<script setup lang="ts">
import { computed, markRaw, ref } from 'vue'
import { Menu, Remove, CirclePlus, Folder, Lock } from '@element-plus/icons-vue'
import { MenuApi } from '@/api/interface/menu'

defineProps(['treeData'])
const emit = defineEmits(['update:modelValue', 'confirm'])
const treeProps = markRaw({
  children: 'children',
  label: 'title'
})
const treeRef = ref()
const beforeClose = () => {
  emit('update:modelValue', false)
}
const isOpen = computed(() => {
  return function (data: MenuApi.Menu) {
    return treeRef.value?.store.nodesMap[data._id].expanded
  }
})
const handleNodeClick = (data: MenuApi.Menu) => {
  emit('confirm', data)
  emit('update:modelValue', false)
}
const handleIconClick = (data: MenuApi.Menu) => {
  treeRef.value.store.nodesMap[data._id].expanded =
    !treeRef.value.store.nodesMap[data._id].expanded
}
</script>

<style lang="scss" scoped>
</style>